"""
错误处理工具模块
提供统一的错误处理和异常管理功能
"""

import traceback
import functools
from typing import Optional, Callable, Any
from core.utils.logger import error, warning, debug, exception


class ErrorHandler:
    """错误处理器"""
    
    @staticmethod
    def handle_import_error(e: ImportError, module_name: str, fallback_action: Optional[Callable] = None) -> bool:
        """处理导入错误
        
        Args:
            e: 导入异常
            module_name: 模块名称
            fallback_action: 备用操作函数
        
        Returns:
            bool: 是否处理成功
        """
        error(f"Failed to import module: {module_name} - {str(e)}")
        if fallback_action:
            try:
                fallback_action()
                return True
            except Exception as fallback_e:
                error(f"Fallback action also failed: {str(fallback_e)}")
        return False
    
    @staticmethod
    def handle_file_operation_error(e: Exception, operation: str, file_path: str, 
                                  fallback_value: Any = None) -> Any:
        """处理文件操作错误
        
        Args:
            e: 异常
            operation: 操作类型（读取、写入等）
            file_path: 文件路径
            fallback_value: 失败时的默认值
        
        Returns:
            操作结果或默认值
        """
        error(f"File operation failed: {operation} {file_path} - {str(e)}")
        return fallback_value
    
    @staticmethod
    def handle_ui_error(e: Exception, component: str, action: str, 
                       user_message: str = None) -> bool:
        """处理UI错误
        
        Args:
            e: 异常
            component: UI组件名称
            action: 操作描述
            user_message: 显示给用户的消息
        
        Returns:
            bool: 是否处理成功
        """
        error(f"UI error: {component} - {action} - {str(e)}")
        if user_message:
            # 这里可以显示用户友好的错误消息
            warning(f"User message: {user_message}")
        return False
    
    @staticmethod
    def handle_business_logic_error(e: Exception, operation: str, 
                                  context: dict = None) -> bool:
        """处理业务逻辑错误
        
        Args:
            e: 异常
            operation: 操作描述
            context: 上下文信息
        
        Returns:
            bool: 是否处理成功
        """
        context_str = f" - Context: {context}" if context else ""
        error(f"Business logic error: {operation}{context_str} - {str(e)}")
        return False
    
    @staticmethod
    def handle_network_error(e: Exception, operation: str, 
                           retry_count: int = 0) -> bool:
        """处理网络错误
        
        Args:
            e: 异常
            operation: 操作描述
            retry_count: 重试次数
        
        Returns:
            bool: 是否处理成功
        """
        error(f"Network error: {operation} (retry {retry_count} times) - {str(e)}")
        return False
    
    @staticmethod
    def handle_validation_error(e: ValueError, field: str, value: Any) -> bool:
        """处理验证错误
        
        Args:
            e: 验证异常
            field: 字段名
            value: 字段值
        
        Returns:
            bool: 是否处理成功
        """
        warning(f"Validation error: field {field} value {value} - {str(e)}")
        return False
    
    @staticmethod
    def safe_execute(func: Callable, *args, default_return: Any = None, 
                    error_message: str = None, **kwargs) -> Any:
        """安全执行函数
        
        Args:
            func: 要执行的函数
            *args: 函数参数
            default_return: 失败时的默认返回值
            error_message: 自定义错误消息
            **kwargs: 函数关键字参数
        
        Returns:
            函数执行结果或默认值
        """
        try:
            return func(*args, **kwargs)
        except Exception as e:
            msg = error_message or f"Failed to execute function {func.__name__}"
            error(f"{msg}: {str(e)}")
            return default_return
    
    @staticmethod
    def log_exception(e: Exception, context: str = ""):
        """记录异常详情
        
        Args:
            e: 异常
            context: 上下文信息
        """
        context_str = f" - Context: {context}" if context else ""
        exception(f"Caught exception{context_str}: {str(e)}")
        debug(f"异常堆栈:\n{traceback.format_exc()}")


class ValidationError(Exception):
    """验证错误异常"""
    pass


class BusinessLogicError(Exception):
    """业务逻辑错误异常"""
    pass


class FileOperationError(Exception):
    """文件操作错误异常"""
    pass


class UIError(Exception):
    """UI错误异常"""
    pass


# 便捷函数
def safe_file_read(file_path: str, encoding: str = 'utf-8', 
                  fallback_data: Any = None) -> Any:
    """安全读取文件"""
    try:
        with open(file_path, 'r', encoding=encoding) as f:
            return f.read()
    except Exception as e:
        return ErrorHandler.handle_file_operation_error(
            e, "read", file_path, fallback_data
        )


def safe_file_write(file_path: str, data: Any, encoding: str = 'utf-8') -> bool:
    """安全写入文件"""
    try:
        with open(file_path, 'w', encoding=encoding) as f:
            f.write(str(data))
        return True
    except Exception as e:
        ErrorHandler.handle_file_operation_error(e, "write", file_path)
        return False


def safe_json_load(file_path: str, fallback_data: Any = None) -> Any:
    """安全加载JSON文件"""
    try:
        import json
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        return ErrorHandler.handle_file_operation_error(
            e, "JSON load", file_path, fallback_data
        )


def safe_json_save(file_path: str, data: Any) -> bool:
    """安全保存JSON文件"""
    try:
        import json
        import os
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        ErrorHandler.handle_file_operation_error(e, "JSON save", file_path)
        return False


# 错误级别枚举
class ErrorLevel:
    """错误级别"""
    FATAL = "fatal"      # Fatal error: program cannot continue
    ERROR = "error"      # Error: operation failed, user attention needed
    WARNING = "warning"  # Warning: operation may have issues but can continue
    INFO = "info"        # Info: normal notification


def handle_errors(level: str = ErrorLevel.ERROR, 
                 user_message: str = None, 
                 show_messagebox: bool = True,
                 log_exception: bool = True):
    """
    Unified error handling decorator
    
    Args:
        level: Error level (fatal, error, warning, info)
        user_message: Message displayed to user (if None, use default message)
        show_messagebox: Whether to show message box
        log_exception: Whether to log exception to log
    """
    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                # 记录异常到日志
                if log_exception:
                    context = f"{func.__module__}.{func.__name__}"
                    ErrorHandler.log_exception(e, context)
                
                # 确定用户消息
                if user_message is None:
                    if level == ErrorLevel.FATAL:
                        msg = f"Fatal system error, program cannot continue: {str(e)}"
                    elif level == ErrorLevel.ERROR:
                        msg = f"Operation failed: {str(e)}"
                    elif level == ErrorLevel.WARNING:
                        msg = f"Operation warning: {str(e)}"
                    else:
                        msg = f"Operation info: {str(e)}"
                else:
                    msg = user_message
                
                # 显示消息框
                if show_messagebox:
                    try:
                        from tkinter import messagebox
                        if level == ErrorLevel.FATAL:
                            messagebox.showerror("Fatal Error", msg)
                        elif level == ErrorLevel.ERROR:
                            messagebox.showerror("Error", msg)
                        elif level == ErrorLevel.WARNING:
                            messagebox.showwarning("Warning", msg)
                        else:
                            messagebox.showinfo("Info", msg)
                    except ImportError:
                        # 如果没有tkinter，则只记录日志
                        warning(f"Cannot display message box: {msg}")
                
                # 根据错误级别决定是否重新抛出异常
                if level == ErrorLevel.FATAL:
                    raise e
                elif level == ErrorLevel.ERROR:
                    # 对于普通错误，返回None或False
                    return None
                else:
                    # 对于警告和信息，继续执行
                    return None
                    
        return wrapper
    return decorator


def handle_fatal_errors(user_message: str = None):
    """处理致命错误的装饰器"""
    return handle_errors(ErrorLevel.FATAL, user_message, True, True)


def handle_critical_errors(user_message: str = None):
    """处理关键错误的装饰器"""
    return handle_errors(ErrorLevel.ERROR, user_message, True, True)


def handle_warnings(user_message: str = None):
    """处理警告的装饰器"""
    return handle_errors(ErrorLevel.WARNING, user_message, True, True)


def handle_info(user_message: str = None):
    """处理信息的装饰器"""
    return handle_errors(ErrorLevel.INFO, user_message, True, False)
